<template>
  <div class="create-component-list">
    <div v-for="(item, index) in list" :key="index" class="component-item" @click="onItemClick(item)">
      <l-text v-bind="item"></l-text>
    </div>
    <styled-uploader @success="onImageUploaded"/>
  </div>
</template>

<script lang="ts">
import { defineComponent, PropType } from 'vue'
import { LText } from 'cool-l-components'
import { ComponentData } from '@/store/editor'
import { v4 as uuidv4 } from 'uuid'
import { TextComponentProps, ImageComponentProps, imageDefaultProps } from 'cool-l-components'
import StyledUploader from '@/components/StyledUploader.vue'
import { message } from 'ant-design-vue'
import { UploadResp } from '../../extraType'
import { getImageDimensions } from '@/utils/helper'
import { SuccessData } from '@/components/Uploader.vue'

export default defineComponent({
  props: {
    list: {
      type: Object,
      required: true
    }
  },
  emits: ['on-item-click'],
  name: 'components-list',
  components: {
    LText,
    StyledUploader
  },
  setup(props, context) {
    const onItemClick = (props: Partial<TextComponentProps>) => {
      const componentData: ComponentData = {
        id: uuidv4(),
        name: 'l-text',
        props
      }
      context.emit('on-item-click', componentData)
    }
    const onImageUploaded = ({ resp, file }: SuccessData) => {
      const componentData: ComponentData = {
        id: uuidv4(),
        name: 'l-image',
        props: {
          ...imageDefaultProps
        }
      }
      message.success('上传成功')
      componentData.props.src = resp.data.url
      getImageDimensions(file).then(({ width, height }) => {
        console.log(width, height)
        componentData.props.width = width + 'px'
        context.emit('on-item-click', componentData)
      })
    }
    return {
      onItemClick,
      onImageUploaded
    }
  }
})
</script>

<style>
.component-item {
  width: 100px;
  margin: 0 auto;
  margin-bottom: 15px;
}
</style>
